﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;

namespace PRO_DOCS.DocumentManagementSystem.ADMIN.WIN.Configurations.EmailsAndWorkflows
{
    public partial class ApplicationWorkflowSteps : BLL.WIN.Templates.DevxConfigurationUserControlTemplate
    {
        DAL.Database.APPLICATION_WORKFLOW CURRENT_SELECTED_APPLICATION_WORKFLOW
        { get; set; }

        List<DAL.Database.APPLICATION_WORKFLOW_STEP> CURRENT_SELECTED_APPLICATION_WORKFLOW_STEPS
        { get; set; }


        DAL.Database.APPLICATION_WORKFLOW_STEP CURRENT_SELECTED_APPLICATION_WORKFLOW_STEP
        { get; set; }

        public ApplicationWorkflowSteps()
        {
            InitializeComponent();

            btnAddNew.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(btnAddNew_ItemClick);
            btnSaveUpdate.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(btnSaveUpdate_ItemClick);
            btnDeleteItem.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(btnDeleteItem_ItemClick);
            btnRefresh.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(btnRefresh_ItemClick);

            CURRENT_SELECTED_APPLICATION_WORKFLOW_STEPS = new List<DAL.Database.APPLICATION_WORKFLOW_STEP>();


            #region LOAD Confirmation Types
            {
                APPLICATION_WORKFLOW_CONFIRMATION_TYPES = new Dictionary<int, int>();
                comboConfirmationTypes.Properties.Items.BeginUpdate();
                comboConfirmationTypes.Properties.Items.Clear();
                int i = 0;
                PRO_DOCSDatabaseDataContext.proc_APPLICATION_WORKFLOW_STEP_CONFIRMATION_TYPESLoadAll().ToList().ForEach(new Action<PRO_DOCS.DAL.Database.proc_APPLICATION_WORKFLOW_STEP_CONFIRMATION_TYPESLoadAllResult>(delegate(PRO_DOCS.DAL.Database.proc_APPLICATION_WORKFLOW_STEP_CONFIRMATION_TYPESLoadAllResult _wORKFLOW_CONFIRMATION)
                {
                    APPLICATION_WORKFLOW_CONFIRMATION_TYPES.Add(i, _wORKFLOW_CONFIRMATION.APPLICATION_WORKFLOW_STEP_CONFIRMATION_TYPE_ID);
                    comboConfirmationTypes.Properties.Items.Add(_wORKFLOW_CONFIRMATION.APPLICATION_WORKFLOW_STEP_CONFIRMATION_TYPE_NAME);
                    i++;
                }));

                comboConfirmationTypes.Properties.Items.EndUpdate();
                comboConfirmationTypes.SelectedIndex = -1;
            }
            #endregion

            #region LOAD System Roles
            {
                APPLICATION_SYSTEM_ROLES = new Dictionary<int, long>();
                comboToSystemRole.Properties.Items.BeginUpdate();
                comboToSystemRole.Properties.Items.Clear();
                int i = 0;
                PRO_DOCSDatabaseDataContext.proc_SYSTEM_ROLESLoadAll().ToList().ForEach(new Action<PRO_DOCS.DAL.Database.proc_SYSTEM_ROLESLoadAllResult>(delegate(PRO_DOCS.DAL.Database.proc_SYSTEM_ROLESLoadAllResult _sYSTEM_ROLE)
                {
                    APPLICATION_SYSTEM_ROLES.Add(i, _sYSTEM_ROLE.ROLE_ID);
                    comboToSystemRole.Properties.Items.Add(_sYSTEM_ROLE.ROLE_NAME);
                    i++;
                }));

                comboToSystemRole.Properties.Items.EndUpdate();
                comboToSystemRole.SelectedIndex = -1;
            }
            #endregion

            #region LOAD System Users
            {
                APPLICATION_SYSTEM_USERS = new Dictionary<int, long>();
                comboToSystemUser.Properties.Items.BeginUpdate();
                comboToSystemUser.Properties.Items.Clear();
                int i = 0;
                PRO_DOCSDatabaseDataContext.proc_LOGIN_USERSLoadAll().ToList().ForEach(new Action<PRO_DOCS.DAL.Database.proc_LOGIN_USERSLoadAllResult>(delegate(PRO_DOCS.DAL.Database.proc_LOGIN_USERSLoadAllResult _lOGIN_USER)
                {
                    APPLICATION_SYSTEM_USERS.Add(i, _lOGIN_USER.LOGIN_USER_ID);
                    comboToSystemUser.Properties.Items.Add(_lOGIN_USER.LOGIN_USER_NAME);
                    i++;
                }));

                comboToSystemUser.Properties.Items.EndUpdate();
                comboToSystemUser.SelectedIndex = -1;
            }
            #endregion


            LOAD_ALL_APPLICATION_WORKFLOWS();
        }

        private void LOAD_ALL_APPLICATION_WORKFLOWS()
        {
            List<DAL.Database.APPLICATION_WORKFLOW> APPLICATION_WORKFLOWS = PRO_DOCSDatabaseDataContext.APPLICATION_WORKFLOWs.ToList();
            gcApplicationWorkFlows.DataSource = APPLICATION_WORKFLOWS;

            if (APPLICATION_WORKFLOWS.Count > 0)
            {
                gvApplicationWorkflows.SelectRow(0);
            }
        }

        private void btnSaveUpdate_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            dxErrorProvider1.ClearErrors();
            bool workflow_step_data_available =
                numStepNumber.Value > 0
                && !string.IsNullOrEmpty(txtStepName.Text)
                && comboConfirmationTypes.SelectedIndex > -1
                && !string.IsNullOrEmpty(txtStepEmail.Text);

            bool workflow_step_to = false;

            if (chkToRole.Checked || chkToUser.Checked)
            {
                if (chkToRole.Checked)
                {
                    workflow_step_to = comboToSystemRole.SelectedIndex > -1;
                }
                if (chkToUser.Checked)
                {
                    workflow_step_to = comboToSystemUser.SelectedIndex > -1;
                }
            }


            if (workflow_step_data_available && workflow_step_to)
            {

                Guid aPPLICATION_WORFLOW_STEP_ID = Guid.Empty;

                long? to_user_id = 0;
                if (comboToSystemUser.SelectedIndex > -1)
                {
                    to_user_id = APPLICATION_SYSTEM_USERS[comboToSystemUser.SelectedIndex];
                }
                else
                {
                    to_user_id = null;
                }

                long? to_role_id = 0;
                if (comboToSystemRole.SelectedIndex > -1)
                {
                    to_role_id = APPLICATION_SYSTEM_ROLES[comboToSystemRole.SelectedIndex];
                }
                else
                {
                    to_role_id = null;
                }

                if (!CURRENT_SELECTED_APPLICATION_WORKFLOW_STEP.APPLICATION_WORKFLOW_STEP_ID.Equals(Guid.Empty)) //update
                {
                    aPPLICATION_WORFLOW_STEP_ID = CURRENT_SELECTED_APPLICATION_WORKFLOW_STEP.APPLICATION_WORKFLOW_STEP_ID;

                    PRO_DOCSDatabaseDataContext.proc_APPLICATION_WORKFLOW_STEPSUpdate
                        (
                            aPPLICATION_WORFLOW_STEP_ID,
                            CURRENT_SELECTED_APPLICATION_WORKFLOW.APPLICATION_WORFLOW_ID,
                            Convert.ToInt32(numStepNumber.Value.ToString()),
                            txtStepName.Text,
                            txtStepEmail.Text,
                            APPLICATION_WORKFLOW_CONFIRMATION_TYPES[comboConfirmationTypes.SelectedIndex],
                            to_user_id,
                            to_role_id
                        );

                    gvApplicationWorkFlowSteps.SetRowCellValue(gvApplicationWorkFlowSteps.FocusedRowHandle, gcStepNumber, numStepNumber.Value.ToString());
                    gvApplicationWorkFlowSteps.SetRowCellValue(gvApplicationWorkFlowSteps.FocusedRowHandle, gcStepName, txtStepName.Text);
                    gvApplicationWorkFlowSteps.SetRowCellValue(gvApplicationWorkFlowSteps.FocusedRowHandle, gcConfirmaitionType, comboConfirmationTypes.Text);
                    gvApplicationWorkFlowSteps.SetRowCellValue(gvApplicationWorkFlowSteps.FocusedRowHandle, gcToUserName, comboToSystemUser.Text);
                    gvApplicationWorkFlowSteps.SetRowCellValue(gvApplicationWorkFlowSteps.FocusedRowHandle, gcToRole, comboToSystemRole.Text);

                }
                else
                {
                    aPPLICATION_WORFLOW_STEP_ID = Guid.NewGuid();

                    PRO_DOCSDatabaseDataContext.proc_APPLICATION_WORKFLOW_STEPSInsert
                        (
                            aPPLICATION_WORFLOW_STEP_ID,
                            CURRENT_SELECTED_APPLICATION_WORKFLOW.APPLICATION_WORFLOW_ID,
                            Convert.ToInt32(numStepNumber.Value.ToString()),
                            txtStepName.Text,
                            txtStepEmail.Text,
                            APPLICATION_WORKFLOW_CONFIRMATION_TYPES[comboConfirmationTypes.SelectedIndex],
                            to_user_id,
                            to_role_id
                        );
                }

                LOAD_CURRENT_SELECTED_APPLICATION_WORKFLOW();
            }
            else
            {

                if (numStepNumber.Value.Equals(0))
                    dxErrorProvider1.SetError(numStepNumber, BLL.WIN.Properties.ErrorProviderMessages.Default.InputLeftBlank.Replace("{name}", "Step number"));

                if (string.IsNullOrEmpty(txtStepName.Text))
                    dxErrorProvider1.SetError(txtStepName, BLL.WIN.Properties.ErrorProviderMessages.Default.InputLeftBlank.Replace("{name}", "Step ame"));

                if (comboConfirmationTypes.SelectedIndex.Equals(-1))
                    dxErrorProvider1.SetError(comboConfirmationTypes, BLL.WIN.Properties.ErrorProviderMessages.Default.InputLeftBlank.Replace("{name}", "Confirmation type"));

                if (string.IsNullOrEmpty(txtStepEmail.Text))
                    dxErrorProvider1.SetError(txtStepEmail, BLL.WIN.Properties.ErrorProviderMessages.Default.InputLeftBlank.Replace("{name}", "Step email notification"));



                if (chkToRole.Checked)
                {
                    if (comboToSystemRole.SelectedIndex.Equals(-1))
                    {
                        dxErrorProvider1.SetError(comboToSystemRole, BLL.WIN.Properties.ErrorProviderMessages.Default.InputLeftBlank.Replace("{name}", "Role name"));
                    }
                }
                else
                {
                    dxErrorProvider1.SetError(chkToRole, BLL.WIN.Properties.ErrorProviderMessages.Default.InputLeftBlank.Replace("{name}", "Role name"));
                }

                if (chkToUser.Checked)
                {
                    if (comboToSystemUser.SelectedIndex.Equals(-1))
                    {
                        dxErrorProvider1.SetError(comboToSystemUser, BLL.WIN.Properties.ErrorProviderMessages.Default.InputLeftBlank.Replace("{name}", "User name"));
                    }
                }
                else
                {
                    dxErrorProvider1.SetError(chkToUser, BLL.WIN.Properties.ErrorProviderMessages.Default.InputLeftBlank.Replace("{name}", "User name"));
                }
            }
        }


        private void gcApplicationWorkFlows_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            CLEAR_WORKFLOW_STEP();

            if (e.FocusedRowHandle > -1)
            {
                

                LOAD_CURRENT_SELECTED_APPLICATION_WORKFLOW();
            }
        }

        private void LOAD_CURRENT_SELECTED_APPLICATION_WORKFLOW()
        {
            CURRENT_SELECTED_APPLICATION_WORKFLOW = gvApplicationWorkflows.GetFocusedRow() as DAL.Database.APPLICATION_WORKFLOW;
            CURRENT_SELECTED_APPLICATION_WORKFLOW = (from workflow in PRO_DOCSDatabaseDataContext.APPLICATION_WORKFLOWs
                                                     where workflow.APPLICATION_WORFLOW_ID.Equals(CURRENT_SELECTED_APPLICATION_WORKFLOW.APPLICATION_WORFLOW_ID)
                                                     select workflow).FirstOrDefault();

            CURRENT_SELECTED_APPLICATION_WORKFLOW_STEPS = CURRENT_SELECTED_APPLICATION_WORKFLOW.APPLICATION_WORKFLOW_STEPs.ToList();
            gcApplicationWorkFlowSteps.DataSource = CURRENT_SELECTED_APPLICATION_WORKFLOW_STEPS;

            if (CURRENT_SELECTED_APPLICATION_WORKFLOW_STEPS.Count > 0)
            {
                gvApplicationWorkFlowSteps.SelectRow(0);
                LOAD_CURRENT_SELECTED_APPLICATION_WORKFLOW_STEP();
            }
            else
            {
                CLEAR_WORKFLOW_STEP();
            }
        }

        private void btnDeleteItem_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (CURRENT_SELECTED_APPLICATION_WORKFLOW_STEP.APPLICATION_WORKFLOW_STEP_ID.Equals(Guid.Empty))
            {
                try
                {
                    PRO_DOCSDatabaseDataContext.proc_APPLICATION_WORKFLOW_STEPSDelete(CURRENT_SELECTED_APPLICATION_WORKFLOW_STEP.APPLICATION_WORKFLOW_STEP_ID);

                    gvApplicationWorkFlowSteps.DeleteSelectedRows();
                }
                catch
                {
                    XtraMessageBox.Show("The current application workflow step cannot be deleted as it is already used in another transaction(s)", "Action denied", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }

        private void btnAddNew_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            CLEAR_WORKFLOW_STEP();
        }

        private void CLEAR_WORKFLOW_STEP()
        {
            CURRENT_SELECTED_APPLICATION_WORKFLOW_STEP = new DAL.Database.APPLICATION_WORKFLOW_STEP();
            numStepNumber.Value = gvApplicationWorkFlowSteps.DataRowCount + 1;
            txtStepName.Text = string.Empty;
            comboConfirmationTypes.SelectedIndex = -1;
            chkToRole.Checked = false;
            comboToSystemRole.SelectedIndex = -1;
            comboToSystemRole.Enabled = false;
            chkToUser.Checked = false;
            comboToSystemUser.SelectedIndex = -1;
            comboToSystemUser.Enabled = false;

        }

        private void btnRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            LOAD_CURRENT_SELECTED_APPLICATION_WORKFLOW();
        }

        public List<DAL.Database.APPLICATION_WORKFLOW> APPLICATION_WORKFLOWS
        { get; set; }

        private void gcApplicationWorkFlowSteps_Click(object sender, EventArgs e)
        {

        }

        public Dictionary<int, int> APPLICATION_WORKFLOW_CONFIRMATION_TYPES { get; set; }

        public Dictionary<int, long> APPLICATION_SYSTEM_USERS { get; set; }

        public Dictionary<int, long> APPLICATION_SYSTEM_ROLES { get; set; }

        private void chkToRole_user_CheckedChanged(object sender, EventArgs e)
        {
            comboToSystemRole.Enabled = chkToRole.Checked;
            comboToSystemRole.SelectedIndex = (comboToSystemRole.Enabled) ? comboToSystemRole.SelectedIndex : -1;

            comboToSystemUser.Enabled = chkToUser.Checked;
            comboToSystemUser.SelectedIndex = (comboToSystemUser.Enabled) ? comboToSystemUser.SelectedIndex : -1;
        }

        private void gvApplicationWorkFlowSteps_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (e.FocusedRowHandle > -1)
            {
                LOAD_CURRENT_SELECTED_APPLICATION_WORKFLOW_STEP();
            }
        }

        private void LOAD_CURRENT_SELECTED_APPLICATION_WORKFLOW_STEP()
        {
            CURRENT_SELECTED_APPLICATION_WORKFLOW_STEP = gvApplicationWorkFlowSteps.GetFocusedRow() as DAL.Database.APPLICATION_WORKFLOW_STEP;

            CURRENT_SELECTED_APPLICATION_WORKFLOW_STEP = (from workflow_step in PRO_DOCSDatabaseDataContext.APPLICATION_WORKFLOW_STEPs
                                                          where workflow_step.APPLICATION_WORKFLOW_STEP_ID.Equals(CURRENT_SELECTED_APPLICATION_WORKFLOW_STEP.APPLICATION_WORKFLOW_STEP_ID)
                                                          select workflow_step).FirstOrDefault();

            numStepNumber.Value = CURRENT_SELECTED_APPLICATION_WORKFLOW_STEP.APPLICATION_WORKFLOW_STEP_NUMBER.Value;
            txtStepName.Text = CURRENT_SELECTED_APPLICATION_WORKFLOW_STEP.APPLICATION_WORKFLOW_STEP_NAME;
            txtStepEmail.Text = CURRENT_SELECTED_APPLICATION_WORKFLOW_STEP.APPLICATION_WORKFLOW_STEP_DESCRIPTION;

            comboConfirmationTypes.Text = CURRENT_SELECTED_APPLICATION_WORKFLOW_STEP.APPLICATION_WORKFLOW_STEP_CONFIRMATION_TYPE.APPLICATION_WORKFLOW_STEP_CONFIRMATION_TYPE_NAME;

            if (CURRENT_SELECTED_APPLICATION_WORKFLOW_STEP.APPLICATION_WORKFLOW_STEP_USER_ID.HasValue)
            {
                chkToUser.Checked = true;
                comboToSystemUser.Text = CURRENT_SELECTED_APPLICATION_WORKFLOW_STEP.LOGIN_USER.EMPLOYEE_FULL_NAME;
                comboToSystemRole.SelectedIndex = -1;
            }

            if (CURRENT_SELECTED_APPLICATION_WORKFLOW_STEP.APPLICATION_WORKFLOW_STEP_SYSTEM_ROLE_ID.HasValue)
            {
                chkToRole.Checked = true;
                comboToSystemRole.Text = CURRENT_SELECTED_APPLICATION_WORKFLOW_STEP.SYSTEM_ROLE.ROLE_NAME;
                comboToSystemUser.SelectedIndex = -1;
            }

        }
    }
}
